import { Store } from '@tauri-apps/plugin-store';

class TauriStoreHelper {
  private store: Store | null = null;
  private storeName: string;
  private initialized: boolean = false;

  constructor(storeName: string = 'store.bin') {
    this.storeName = storeName;
  }

  // 初始化存储
  private async ensureInitialized(): Promise<void> {
    if (!this.initialized) {
      this.store = await Store.load(this.storeName);
      this.initialized = true;
    }
  }

  /**
   * 获取存储值
   * @param key 键名
   * @returns 对应的值，如果不存在则返回 null
   */
  public async get<T = any>(key: string): Promise<T | null> {
    await this.ensureInitialized();
    return (await this.store?.get(key)) ?? null;
  }

  /**
   * 设置存储值并自动保存
   * @param key 键名
   * @param value 要存储的值
   */
  public async set(key: string, value: any): Promise<void> {
    await this.ensureInitialized();
    await this.store?.set(key, value);
    await this.store?.save(); // 自动保存
  }

  /**
   * 删除存储中的键并自动保存
   * @param key 要删除的键名
   */
  public async delete(key: string): Promise<void> {
    await this.ensureInitialized();
    await this.store?.delete(key);
    await this.store?.save(); // 自动保存
  }

  /**
   * 清空存储并自动保存
   */
  public async clear(): Promise<void> {
    await this.ensureInitialized();
    await this.store?.clear();
    await this.store?.save(); // 自动保存
  }

  /**
   * 获取所有键名
   * @returns 存储中的所有键名数组
   */
  public async keys(): Promise<string[]> {
    await this.ensureInitialized();
    return (await this.store?.keys()) ?? [];
  }

  /**
   * 获取存储中的所有值
   * @returns 包含所有键值对的对象
   */
  public async values(): Promise<Record<string, any>> {
    await this.ensureInitialized();
    const keys = await this.keys();
    const result: Record<string, any> = {};
    
    for (const key of keys) {
      result[key] = await this.get(key);
    }
    
    return result;
  }

  /**
   * 手动保存存储
   */
  public async save(): Promise<void> {
    await this.ensureInitialized();
    await this.store?.save();
  }
}

// 默认导出一个实例
const storeHelper = new TauriStoreHelper();
export default storeHelper;